<?php

/**
 * PrivateMessageModel
 *  
 * @author Nguyen Hai Ha
 * @version 
 */

class PmModel {
	/**
	 * The default table name 
	 */
	protected $_name = 'eway_pm';
	protected $_dbAdapter;
	
	function PmModel(){
		$this->_dbAdapter = Zend_Registry::get(Constant::DB_ADAPTER);
	}
		
	function getTotalRecords($account){
		$sql = "SELECT COUNT(*) FROM ".$this->_name." WHERE pm_to=?";				
		$result = $this->_dbAdapter->fetchCol($sql, $account);				
		return $result[0];		
	}
	
	public function getAllMessage($account, $currentPages, $recordPerPage){
		$offset = ($currentPages - 1) * $recordPerPage;
		$sql = "SELECT u.usr_fullname name, p.* FROM ".$this->_name." p 
		INNER JOIN  eway_user u 
		ON p.pm_from = u.usr_mobile  
		WHERE p.pm_to=? ORDER BY pm_date DESC 
		LIMIT $offset,$recordPerPage";

		$result = $this->_dbAdapter->fetchAll($sql, $account);
		return $result;		
	}
	
	function getTotalRecordsSent($account){
		$sql = "SELECT COUNT(*) FROM ".$this->_name." WHERE pm_from=?";				
		$result = $this->_dbAdapter->fetchCol($sql, $account);				
		return $result[0];		
	}
	
	public function getAllMessageSent($account, $currentPages, $recordPerPage){
		$offset = ($currentPages - 1) * $recordPerPage;
		$sql = "SELECT u.usr_fullname name, p.* FROM " . $this->_name ." p "
		. "INNER JOIN  eway_user u " 
		. "ON p.pm_to = u.usr_mobile "  
		. "WHERE p.pm_from=? ORDER BY pm_date DESC " 
		. "LIMIT $offset,$recordPerPage";

		$result = $this->_dbAdapter->fetchAll($sql, $account);
		return $result;		
	}
	
	public function getMessageById($message_id){
		$sql = "SELECT u.usr_fullname name, p.* FROM " .$this->_name ." p " 
		. "INNER JOIN  eway_user u " 
		. "ON p.pm_from = u.usr_mobile "
		. "WHERE pm_id=?";
		$result = $this->_dbAdapter->fetchRow($sql, $message_id);
		return $result;
	}
	
	public function insert( $pm = array() ) {
		$this->_dbAdapter->insert ( $this->_name, $pm );
		$id = $this->_dbAdapter->lastInsertId ();
		return $id;
	}
	
	public function delete( $pm_id ){
		$where = "pm_id=".$pm_id;
		$this->_dbAdapter->delete( $this->_name, $where );
	}
}
